package com.tony.business.config;

import com.tony.domain.bo.JsonResult;
import com.tony.domain.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashSet;
import java.util.Set;

/**
 * @author x
 * @date 2019/8/2 14:28
 */
@RestControllerAdvice
@Slf4j
public class ErrorAdvice {

    @ExceptionHandler(Exception.class)
    public JsonResult<?> exception(Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        log.error(sw.getBuffer().toString());
        return new JsonResult<>(e);
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<?> exception(BindException e) {
        Set<String> set = new HashSet<>(e.getErrorCount());
        for (FieldError error : e.getFieldErrors()) {
            set.add(error.getField() + error.getDefaultMessage());
        }
        return new JsonResult<>(e, set);
    }

    @ExceptionHandler(CustomException.class)
    public JsonResult<?> exception(CustomException e) {
        return new JsonResult<>(e);
    }

}
